from django.db import models
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
import dmarkups

class Markup(models.Model):
    markup = models.CharField(name=_('Markup'), max_length=128, 
                              help_text=_('The formatting language you wish to use for this text.'))
    content = models.TextField(name=_('Content'))
    rendered_content = models.TextField(editable=False)
    
    modified = models.DateTimeField(default=datetime.now, editable=False)
    created = models.DateTimeField(default=datetime.now, editable=False)
    
    def render(self):
        # TODO: Settings to markup functions? Do we need to pass settings or something like that 
        markup_name, markup_function = dmarkups.MARKUP_CHOICES.get(self.markup, lambda text: text)
        try:
            self.rendered_content = markup_function(self.content)
        except dmarkups.MarkupRenditionError:
            self.rendered_content = self.content
        return self.rendered_content
    
    def save(self, force_insert=False, force_update=False, render=True):
        self.modified = datetime.now()
        # TODO: Saving auto rendering, good idea?
        if render:
            self.render()
        super(Markup, self).save(force_insert=force_insert, force_update=force_update)
    
    def __unicode__(self):
        # TODO: or self.content? Might not be expected...
        return self.rendered_content or self.content